import { ref } from 'vue';
import { message } from 'ant-design-vue';
import router from '@/router/index.js';
import { REQU, getTaskInfo, getUserInfo, toFormData, useResp } from '@/net/requ.js';
import { asgmntGte } from '@/util/index.js';

const AssignmentInfo = R.compose( R.curryN(1, JSON.stringify), R.project(['userId', 'fileNum']) );

export function useTaskAssign({ id, fileTotal }) {
  const loading = ref(false);
  const taskInfo = ref(null);
  const singlePackageNum = ref(20);
  const dataSource = ref([]);

  function main() {
    loading.value = true;
    getTaskInfo(id)
    .then( useResp({ succ: R.prop('data') }) )
    .then(value => {
      if (asgmntGte('已分配', value)) {
        message.warning('此任务已分配')
        router.replace({ path: 'task-list', query: { id } });
        return [];
      }
  
      taskInfo.value = value;
      return R.compose( R.split(','), R.prop('tagUserIds') )(value);
    })
    .then(userIds => Promise.all( userIds.map(getUserInfo) ))
    .then(userInfos => userInfos.map(o => ({ userId: o.id, realName: o.realName, fileNum: 0 })))
    .then(tableData => (dataSource.value = tableData))
    .finally(() => (loading.value = false));
  }

  function submit(params) {
    loading.value = true;
    return REQU('/api/task/assignment', {
      method: 'POST',
      body: toFormData(Object.assign(
        {
          id,
          assignmentInfo: AssignmentInfo(dataSource.value),
          singlePackageNum: singlePackageNum.value,
          fileTotal: fileTotal.value
        },
        params
      ))
    })
    .then(useResp({
      succ: () => {
        message.success('分配完成');
        router.push('/task')
      }
    }))
    .catch(() => {})
    .finally(() => (loading.value = false));
  }

  return {
    loading,
    taskInfo,
    singlePackageNum,
    dataSource,
    main,
    submit,
  };
}
